<template>
  <div class="campaigns-page">
    <el-container>
      <el-header class="header">
        <div class="header-content">
          <h1 class="logo">众筹平台</h1>
          <el-menu
            mode="horizontal"
            :default-active="activeMenu"
            class="nav-menu"
            @select="handleMenuSelect"
          >
            <el-menu-item index="/home">首页</el-menu-item>
            <el-menu-item index="/campaigns">众筹列表</el-menu-item>
            <el-menu-item index="/create">创建众筹</el-menu-item>
            <el-menu-item index="/my-campaigns">我的众筹</el-menu-item>
          </el-menu>
          <div class="user-info">
            <span class="username">{{ user.username }}</span>
            <el-button type="text" @click="logout">退出</el-button>
          </div>
        </div>
      </el-header>
      
      <el-main class="main-content">
        <div class="campaigns-container">
          <div class="page-header">
            <h2>所有众筹项目</h2>
            <el-button type="primary" icon="el-icon-refresh" @click="loadCampaigns">
              刷新
            </el-button>
          </div>

          <el-alert
            v-if="!walletConnected"
            title="提示"
            type="warning"
            description="请先连接钱包以查看众筹项目"
            show-icon
            :closable="false"
            style="margin-bottom: 20px;"
          >
            <el-button type="primary" size="small" @click="connectWallet">
              连接钱包
            </el-button>
          </el-alert>

          <div v-loading="loading" class="campaigns-grid">
            <el-empty v-if="campaigns.length === 0 && !loading" description="暂无众筹项目" />
            
            <el-card
              v-for="campaign in campaigns"
              :key="campaign.id"
              class="campaign-card"
              shadow="hover"
              @click.native="goToDetail(campaign.id)"
            >
              <div class="campaign-status">
                <el-tag :type="getStatusType(campaign.status)">
                  {{ campaign.status }}
                </el-tag>
              </div>
              
              <h3 class="campaign-name">{{ campaign.name }}</h3>
              <p class="campaign-description">{{ campaign.description }}</p>
              
              <div class="campaign-progress">
                <el-progress
                  :percentage="campaign.progress"
                  :color="getProgressColor(campaign.progress)"
                />
                <div class="progress-info">
                  <span>已筹集: {{ campaign.pledged }} ETH</span>
                  <span>目标: {{ campaign.goal }} ETH</span>
                </div>
              </div>
              
              <div class="campaign-time">
                <i class="el-icon-time"></i>
                <span v-if="campaign.status === 'Active'">
                  剩余时间: {{ getRemainingTime(campaign.endAt) }}
                </span>
                <span v-else>
                  {{ formatDate(campaign.endAt) }} 结束
                </span>
              </div>
              
              <div class="campaign-creator">
                <i class="el-icon-user"></i>
                创建者: {{ shortAddress(campaign.creator) }}
              </div>
            </el-card>
          </div>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import web3Helper from '@/utils/web3';
import contractService from '@/api/contract';

export default {
  name: 'Campaigns',
  data() {
    return {
      user: {},
      walletConnected: false,
      campaigns: [],
      loading: false,
      activeMenu: '/campaigns'
    };
  },
  created() {
    this.loadUserInfo();
    this.checkWalletConnection();
  },
  methods: {
    loadUserInfo() {
      const userStr = localStorage.getItem('user');
      if (userStr) {
        this.user = JSON.parse(userStr);
      }
    },
    
    async checkWalletConnection() {
      if (web3Helper.getAccount()) {
        this.walletConnected = true;
        await this.loadCampaigns();
      }
    },
    
    async connectWallet() {
      try {
        await web3Helper.connect();
        this.walletConnected = true;
        await contractService.init();
        await this.loadCampaigns();
        this.$message.success('钱包连接成功！');
      } catch (error) {
        this.$message.error(error.message || '钱包连接失败');
      }
    },
    
    async loadCampaigns() {
      if (!this.walletConnected) return;
      
      this.loading = true;
      try {
        await contractService.init();
        const ids = await contractService.getAllCampaignIds();
        
        const campaigns = [];
        for (const id of ids) {
          try {
            const campaign = await contractService.getCampaign(id);
            const status = await contractService.getCampaignStatus(id);
            
            const pledged = parseFloat(campaign.pledged);
            const goal = parseFloat(campaign.goal);
            const progress = goal > 0 ? Math.min((pledged / goal) * 100, 100) : 0;
            
            campaigns.push({
              id,
              ...campaign,
              status,
              progress: Math.round(progress)
            });
          } catch (error) {
            console.error(`加载众筹 ${id} 失败:`, error);
          }
        }
        
        this.campaigns = campaigns.reverse(); // 最新的在前面
      } catch (error) {
        console.error('加载众筹列表失败:', error);
        this.$message.error(error.message || '加载众筹列表失败');
      } finally {
        this.loading = false;
      }
    },
    
    goToDetail(id) {
      this.$router.push(`/campaign/${id}`);
    },
    
    getStatusType(status) {
      const typeMap = {
        'Active': 'success',
        'Successful': 'success',
        'Failed': 'danger',
        'Cancelled': 'warning',
        'Not Started': 'info'
      };
      return typeMap[status] || 'info';
    },
    
    getProgressColor(percentage) {
      if (percentage < 30) return '#F56C6C';
      if (percentage < 70) return '#E6A23C';
      return '#67C23A';
    },
    
    getRemainingTime(endAt) {
      const now = Math.floor(Date.now() / 1000);
      const remaining = endAt - now;
      
      if (remaining <= 0) return '已结束';
      
      const days = Math.floor(remaining / 86400);
      const hours = Math.floor((remaining % 86400) / 3600);
      const minutes = Math.floor((remaining % 3600) / 60);
      
      if (days > 0) return `${days}天 ${hours}小时`;
      if (hours > 0) return `${hours}小时 ${minutes}分钟`;
      return `${minutes}分钟`;
    },
    
    formatDate(timestamp) {
      const date = new Date(timestamp * 1000);
      return date.toLocaleString('zh-CN');
    },
    
    shortAddress(address) {
      if (!address) return '';
      return `${address.substring(0, 6)}...${address.substring(38)}`;
    },
    
    handleMenuSelect(index) {
      this.$router.push(index);
    },
    
    logout() {
      this.$confirm('确定要退出登录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        localStorage.removeItem('user');
        web3Helper.disconnect();
        this.$message.success('已退出登录');
        this.$router.push('/login');
      }).catch(() => {});
    }
  }
};
</script>

<style scoped>
.campaigns-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header {
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 0;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  height: 100%;
  padding: 0 20px;
}

.logo {
  font-size: 24px;
  color: #409EFF;
  margin: 0;
  margin-right: 40px;
}

.nav-menu {
  flex: 1;
  border: none;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.username {
  font-weight: bold;
  color: #333;
}

.main-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.campaigns-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}

.campaign-card {
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
}

.campaign-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.15);
}

.campaign-status {
  position: absolute;
  top: 15px;
  right: 15px;
}

.campaign-name {
  margin: 0 0 15px 0;
  font-size: 20px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.campaign-description {
  color: #666;
  margin-bottom: 20px;
  height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.campaign-progress {
  margin-bottom: 15px;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  font-size: 14px;
  color: #666;
}

.campaign-time,
.campaign-creator {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 14px;
  color: #666;
  margin-top: 10px;
}

.campaign-time i,
.campaign-creator i {
  color: #409EFF;
}
</style>

